<template>
  <div class="commonTable" v-loading="loading">
    <div class="commonTable-title">
      <span>{{ data.name }}</span>
    </div>
    <div class="commonTable-date">
      <!-- 日期 -->
      <p v-if="screenTime && screenTime.length != 0">
        <span class="left">{{ new Date(screenTime[0]).format("yyyy-MM-dd") }} ~ {{ new Date(screenTime[1]).format("yyyy-MM-dd") }}</span>
      </p>
      <p v-else>
        <span v-if="data.relativelyTime || data.relativelyTime == 0" class="left">{{ relativelyTimeDeal.format("yyyy-MM-dd") }} ~ {{ new Date().format("yyyy-MM-dd") }}</span>
        <span v-else class="left">{{ new Date(data.startTime).format("yyyy-MM-dd") }} ~ {{ new Date(data.endTime).format("yyyy-MM-dd") }}</span>
      </p>
      <!-- el-tooltip -->
      <p class="tooltip-p" v-if="screenTime && screenTime.length != 0">
        <el-tooltip content="筛选时段" placement="bottom" effect="light">
          <img class="right" :src="dateIcon" alt="">
        </el-tooltip>
      </p>
      <p class="tooltip-p" v-else>
        <el-tooltip v-if="data.relativelyTime || data.relativelyTime == 0" :content="`统计时段 相对${ data.relativelyTime/3600/1000/24 == 0 ? '今' : data.relativelyTime/3600/1000/24 }天时段`" placement="bottom" effect="light">
          <img class="right" :src="dateIcon" alt="">
        </el-tooltip>
        <el-tooltip v-else content="统计时段 固定时段" placement="bottom" effect="light">
          <img class="right" :src="dateIcon" alt="">
        </el-tooltip>
      </p>
    </div>
    <!-- elementUI table二次封装 -->
    <div class="commonTable-table" v-if="payloadData.dayData && payloadData.dayData.length != 0">
      <el-table
        :data="tableData"
        max-height="230px"
        style="width: 100%;height: 230px;"
        header-cell-class-name="headerCellClass">
        <template
          v-for="(item, index) in column"
          :key="index">
          <el-table-column
            :width="item.width?item.width:'auto'"
            :prop="item.prop"
            :align="item.align?item.align:'center'"
            :label="item.label">
            <template
              #default="scope"
              v-if="item.isNested?item.isNested:false">
              <el-table-column
                v-for="(value, key) in item.childrenColumn"
                :key="key"
                :width="value.width?value.width:'auto'"
                :prop="value.prop"
                :align="value.align?value.align:'center'"
                :label="value.label">
                <template #default="scope">
                  <slot v-if="value.slot" :name="value.prop" :row="scope.row"></slot>
                  <template v-else>
                    {{ scope.row[value.prop] }}
                  </template>
                </template>
              </el-table-column>
            </template>
            <template #default="scope" v-else>
              <slot v-if="item.slot" :name="item.prop" :row="scope.row"></slot>
              <template v-else>
                {{ scope.row[item.prop] }}
              </template>
            </template>
          </el-table-column>
        </template>
      </el-table>
      <el-pagination 
        class="pagination"
        @current-change="handleCurrentChange"
        :current-page="pageVo.currentPage"
        :page-size="pageVo.pageSize"
        layout="total, prev, pager, next, jumper"
        :total="pageVo.total">
      </el-pagination>
    </div>
    <!-- empty -->
    <el-empty v-else :image="emptyImg" description="暂无数据" :image-size="80" style="width: 100%;height: 272px;"></el-empty>
  </div>
</template>

<script>
// vuex
import store from "@/store";
// 图片
import dateIcon from '@/assets/dataCenter/dataB_dateIcon.png';
import emptyImg from '@/assets/dataCenter/dataB_empty.png';
// API
import {
  dataBoardByChartId,
  dataBoardMerchantGetChatData
} from '@/api/dataCenter/dataBoard.js';
// utils
import { dateStrChangeTimeTamp } from './utils.js';

export default {
  name: 'CommonTable',
  props: {
    id: {
      type: Number,
      default: () => {
        return null;
      }
    },
    tableData: {
      type: Array,
      default: () => {
        return [
          {
              id:"1",
              name:"张三",
              sex:0,
              age:12,
              grade:1,
              desc:"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
          },
          {
              id:"2",
              name:"李四",
              sex:0,
              age:13,
              grade:2,
              desc:"HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH"
          },
          {
              id:"3",
              name:"李丽",
              sex:1,
              age:13,
              grade:2,
              desc:"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
          }
        ];
      }
    },
    column: {
      type: Array,
      default: () => {
        return [
          {
              prop:"id",
              align:"",
              label:"ID",
              scopeStatus:true,
              width:"",
              minWidth:""
          },
          {
              prop:"name",
              align:"",
              label:"姓名",
              scopeStatus:false,
              width:"",
              minWidth:""
          },
          {
              prop:"sex",
              align:"",
              label:"性别",
              scopeStatus:true,
              width:"",
              minWidth:""
          },
          {
              prop:"age",
              align:"",
              label:"年龄",
              scopeStatus:false,
              width:"",
              minWidth:""
          },
          {
              prop:"grade",
              align:"",
              label:"年级",
              scopeStatus:true,
              width:"",
              minWidth:""
          },
          {
              prop:"desc",
              align:"",
              label:"描述",
              scopeStatus:true,
              width:"",
              minWidth:""
          }
        ];
      }
    }
  },
  data() {
    return {
      loading: false,
      dateIcon,
      emptyImg,
      loading: false,
      data: {},
      payloadData: {},
      relativelyTimeDeal: null,
      column: [
        {
          prop: 'date',
          align: '',
          label: '日期',
          scopeStatus:false,
          width:"",
        }
      ],
      tableData: [],
      pageVo: {
        currentPage: 1,
        pageSize: 10,
        total: 100
      }
    }
  },
  watch: {
    screenTime: {
      handler(val) {
        this.dataBoardMerchantGetChatDataApi();
      },
      deep: true
    },
    organizationId: {
      handler(val) {
        this.dataBoardMerchantGetChatDataApi();
      },
      deep: true
    }
  },
  mounted() {
    this.dataBoardByChartIdApi();
  },
  methods: {
    exportExcel(excelName) {
      try {
        const $e = this.$refs['report-table'].$el
        let $table = $e.querySelector('.el-table__fixed')
        if(!$table) {
          $table = $e
        }

        const wb = XLSX.utils.table_to_book($table, {raw:true})
        const wbout = XLSX.write(wb, {bookType: 'xlsx', bookSST:true, type: 'array'})
        FileSaver.saveAs(
          new Blob([wbout],{type: 'application/octet-stream'}),
          `${excelName}.xlsx`,
        )
      } catch (e) {
        if (typeof console !== 'undefined') console.error(e)
      }
    },
    // 获取报表数据
    async dataBoardByChartIdApi() {
      let res = await dataBoardByChartId({
        id: this.id
      });
      if(res.code === 200) {
        this.data = res.payload;
        let start = new Date()
        start.setTime(start.getTime() - this.data.relativelyTime)
        this.relativelyTimeDeal = start;
        if(this.data.relativelyTime === 0) {
          this.relativelyTimeDeal = new Date();
        }
        // 获取chart数据
        this.dataBoardMerchantGetChatDataApi();
      }
    },
    // 获取报表具体数据
    async dataBoardMerchantGetChatDataApi() {
      this.loading = true;
      let startTime;
      let endTime;
      let screenTime = store.state.user.screenTime;
      if(screenTime && screenTime.length != 0) {
        startTime = dateStrChangeTimeTamp(screenTime[0]);
        endTime = dateStrChangeTimeTamp(screenTime[1]);
      } else {
        // startTime 和 endTime存在即固定时间
        if(this.data.startTime && this.data.endTime) {
          startTime = this.data.startTime;
          endTime = this.data.endTime;
        }
        // relativelyTime存在即相对时间
        if(this.data.relativelyTime) {
          let nowDate = new Date().getTime();
          let startDate = nowDate - this.data.relativelyTime;
          startTime = startDate;
          endTime = nowDate;
        }
      }
      let res = await dataBoardMerchantGetChatData({
        id: this.id,
        startTime,
        endTime,
        insId: store.state.insId.insId,
        currentPage: this.pageVo.currentPage,
        showCount: this.pageVo.pageSize
      })
      if(res.code === 200) {
        this.payloadData = res.payload;
        this.pageVo.total = res.payload.total;
        if(this.payloadData && this.payloadData.dayData.length != 0)  {
          this.capsulationDealData();
        } else {
          this.loading = false;
        }
      }
    },
    // 处理数据封装
    capsulationDealData() {
      // 1、区分分组和不分组情况
      if(this.payloadData.groupColumn && this.payloadData.groupColumn.indexOf('columnHumpName') != -1) {
      // 1.1分组逻辑
        let specialColumn = [];
        let indicatorsColumn = ''; // 分组表格首个表头
        let columnHumpName = ''; // 获取数据存储字段
        let groupColumn = JSON.parse(this.payloadData.groupColumn.replace(/\\/g, ''));
        indicatorsColumn = groupColumn[0].columnDesc;
        columnHumpName = groupColumn[0].columnHumpName;

        if(this.payloadData.specialColumn.indexOf(',') != -1) { // 多指标
          // 处理表头
          let dealSpecialColumn = this.payloadData.specialColumn.replace('{', '').replace('}', '').split(', ');
          dealSpecialColumn.forEach(item => {
            let obj = {};
            obj.enVal = item.split('=')[0];
            obj.chnVal = item.split('=')[1];
            specialColumn.push(obj);
          })
          console.log(specialColumn, 'specialColumn')
          this.column = [
            {
              prop: 'totalColumn',
              align: '',
              label: indicatorsColumn,
              scopeStatus:false,
              width:"",
            },
            {
              align: '',
              label: '合计',
              scopeStatus:false,
              width:"",
              isNested: true,
              childrenColumn: []
            }
          ];
          // 处理合计列表头
          specialColumn.forEach(item => {
            let obj = {
              prop: '',
              align: '',
              label: '',
              scopeStatus:false,
              width:"",
            }
            obj.prop = item.enVal;
            obj.label = item.chnVal;
            this.column[1].childrenColumn.push(obj);
          })
          console.log('this.column', this.column);

          // 处理具体数据
          let dayData = [];
          dayData = JSON.parse(JSON.stringify(this.payloadData.dayData));
          dayData.forEach(item => {
            item.time = new Date(item.createTime).format("yyyy-MM-dd");
            item.dayData = JSON.parse(item.dayData.replace(/\\/g, ''));
          })
          console.log('dayData', dayData)
          // 提取第一列
          let tableDataStep1 = [];
          dayData.forEach((item, index) => {
            if(index === 0) {
              item.dayData.forEach(val => {
                let obj = {};
                for(let i in val) {
                  if(String(columnHumpName) === String(i)) {
                    obj['totalColumn'] = val[i];
                  } else {
                    obj[i] = 0;
                  }
                }
                tableDataStep1.push(obj);
              })
            }
          })
          dayData.forEach(item => {
            item.time = new Date(item.createTime).format("yyyy-MM-dd");
            item.dayData.forEach(val1 => {
              tableDataStep1.forEach(val2 => {
                if(val1[columnHumpName] === val2.totalColumn) {
                  for(let i in val1) {
                    for(let j in val2) {
                      if(i === j) {
                        val2[j] += Number(val1[i]);
                      }
                    }
                  }
                } 
              })
            })
          })

          dayData.forEach(item => {
            item.dayData.forEach(val1 => {
              tableDataStep1.forEach(val2 => {
                if(val1[columnHumpName] === val2.totalColumn) {
                  for(let i in val1) {
                    for(let j in val2) {
                      if(i === j) {
                        val2[i + item.time] = val1[i];
                      }
                    }
                  }
                } 
              })
            })
          })
          console.log('tableDataStep1', tableDataStep1)
          this.tableData = tableDataStep1;

          // 处理剩余日期表头
          dayData.forEach(item => {
            let obj1 = {
              align: '',
              label: item.time,
              scopeStatus:false,
              width:"",
              isNested: true,
              childrenColumn: []
            }
            specialColumn.forEach(val1 => {
              let obj2 = {
                prop: '',
                align: '',
                label: '',
                scopeStatus:false,
                width:"",
              }
              item.dayData.forEach(val2 => {
                for(let i in val2) {
                  if(i === val1.enVal) {
                    obj2.prop = val1.enVal + item.time;
                    obj2.label = val1.chnVal;
                  }
                }
              })
              obj1.childrenColumn.push(obj2)
            })
            this.column.push(obj1)
          })
          console.log('this.column', this.column)
        } else { // 单指标
          // 处理表头
          specialColumn = this.payloadData.specialColumn.replace('{', '').replace('}', '').split('=')[0];
          this.column = [
            {
              prop: columnHumpName,
              align: '',
              label: indicatorsColumn,
              scopeStatus:false,
              width:"",
            },
            {
              prop: 'totalColumn',
              align: '',
              label: '合计',
              scopeStatus:false,
              width:"",
            }
          ];
          this.payloadData.dayData.forEach(item => {
            let obj = {
              prop: new Date(item.createTime).format("yyyy-MM-dd"),
              align: '',
              label: new Date(item.createTime).format("yyyy-MM-dd"),
              scopeStatus:false,
              width:"",
            }
            this.column.push(obj);
          })

          // 处理数据
          let dayData = [];
          dayData = JSON.parse(JSON.stringify(this.payloadData.dayData));
          dayData.forEach(item => {
            item.time = new Date(item.createTime).format("yyyy-MM-dd");
            item.dayData = JSON.parse(item.dayData.replace(/\\/g, ''));
          })
          console.log('dayData', dayData)
          // 提取每个日期对应的数据
          let tableDataStep1 = [];
          dayData.forEach(item => {
            item.dayData.forEach(val => {
              let obj = {
                time: item.time,
              }
              for(let i in val) {
                if(String(specialColumn) === String(i)) {
                  obj[i] = val[i]
                }
                if(String(columnHumpName) === String(i)) {
                  obj[i] = val[i]
                }
              }
              tableDataStep1.push(obj);
            })
          })
          console.log('tableDataStep1', tableDataStep1)
          // 计算整合合计数据
          let tableDataStep2 = [];
          let arr = [];
          tableDataStep1.forEach(item => {
            for(let i in item) {
              if(String(columnHumpName) === String(i)) {
                arr.push(item[i]);
              }
            }
          })
          arr = Array.from(new Set(arr));
          console.log('arr', arr)
          arr.forEach(item => {
            let num = 0;
            tableDataStep1.forEach(val => {
              for(let i in val) {
                if(val[i] === item) {
                  num += Number(val[specialColumn])
                }
              }
            })
            let obj = {}
            obj[columnHumpName] = item;
            obj.totalColumn = num;
            tableDataStep2.push(obj);
          })
          console.log('tableDataStep2', tableDataStep2)
          // 整合统计和日期数据
          tableDataStep2.forEach(item => {
            tableDataStep1.forEach(val => {
              if(item[columnHumpName] === val[columnHumpName]) {
                item[val.time] = val[specialColumn]
              }
            })
          })
          this.tableData = tableDataStep2;
        }
      } else {
      // 1.2不分组逻辑
        let specialColumn = [];
        // 具体数值字段获取
        if(this.payloadData.specialColumn && this.payloadData.specialColumn.indexOf(',') != -1) { // 多指标
          let dealSpecialColumn = this.payloadData.specialColumn.replace('{', '').replace('}', '').split(', ');
          dealSpecialColumn.forEach(item => {
            let obj = {};
            obj.enVal = item.split('=')[0];
            obj.chnVal = item.split('=')[1];
            specialColumn.push(obj);
          })
          this.column = [
            {
              prop: 'date',
              align: '',
              label: '日期',
              scopeStatus:false,
              width:"",
            }
          ]
          specialColumn.forEach(item => {
            let obj = {
              prop: item.enVal,
              align: '',
              label: item.chnVal,
              scopeStatus:false,
              width:"",
            }
            this.column.push(obj);
          })
        } else { // 单指标
          specialColumn = this.payloadData.specialColumn.replace('{', '').replace('}', '').split('=');
          this.column = [
            {
              prop: 'date',
              align: '',
              label: '日期',
              scopeStatus:false,
              width:"",
            }
          ];
          let obj = {
            prop: specialColumn[0],
            align: '',
            label: specialColumn[1],
            scopeStatus:false,
            width:"",
          }
          this.column.push(obj);
        }
        // 处理具体数据
        // Step1
        let chartData = [];
        this.payloadData.dayData.forEach(item => {
          let obj = {};
          obj.date = new Date(item.createTime).format("yyyy-MM-dd");
          obj.id = item.id
          obj.insId = item.insId
          obj.reportId = item.reportId
          obj.value = JSON.parse(item.dayData.replace(/\\/g, ''));
          let objVal = Object.assign({}, obj, obj.value[0]);
          chartData.push(objVal);
        });
        // 合计
        if(this.payloadData.specialColumn && this.payloadData.specialColumn.indexOf(',') != -1) { // 多指标
          let totalArr = [];
          specialColumn.forEach((item, index) => {
            let totalObj = {
              num: 0,
              enVal: ''
            }
            chartData.forEach((val, key) => {
              for(let i in val) {
                if(String(item.enVal) === String(i)) {
                  totalObj.enVal = item.enVal;
                  totalObj.num += Number(val[i]);
                }
              }
            })
            totalArr.push(totalObj);
          })
          this.tableData = JSON.parse(JSON.stringify(chartData));
          this.tableData.unshift(chartData[chartData.length -1]);
          this.tableData.forEach((item, index) => {
            if(index === 0) {
              item.date = '合计'
              totalArr.forEach(val => {
                for(let i in item) {
                  if(val.enVal === String(i)) {
                    item[i] = val.num;
                  }
                }
              })
            }
          })
        } else { // 单指标
          let totalNum = 0;
          chartData.forEach(item => {
            for(let i in item) {
              if(String(specialColumn[0]) === String(i)) {
                totalNum += Number(item[i]);
              }
            }
          })
          this.tableData = JSON.parse(JSON.stringify(chartData));
          this.tableData.unshift(chartData[chartData.length -1]);
          this.tableData.forEach((item, index) => {
            if(index === 0) {
              item.date = '合计'
              for(let i in item) {
                if(String(specialColumn[0]) === String(i)) {
                  item[i] = totalNum;
                }
              }
            }
          })
        }
      }
      // 关闭loading
      this.loading = false;
    },
    // 切换页数
    handleCurrentChange(val) {
      this.pageVo.currentPage = val;
      // 更新数据
      this.dataBoardMerchantGetChatDataApi();
    }
  },
  computed: {
    screenTime() {
      return store.state.user.screenTime;
    },
    organizationId() {
      return store.state.insId.insId;
    }
  }
}
</script>

<style lang="scss" scoped>
.commonTable {
  width: 100%;
  height: 100%;
  &-title {
    width: 100%;
    height: 36px;
    display: flex;
    align-items: center;
    justify-content: flex-start;
    span {
      color: #252934;
      height: 24px;
      // width: 112px;
      font-family: PingFangSC-Medium;
      font-size: 16px;
      line-height: 24px;
      cursor: pointer;
    }
  }
  &-date {
    width: 100%;
    height: 16px;
    display: flex;
    align-items: center;
    justify-content: flex-start;
    margin-bottom: 34px;
    .left {
      font-size: 12px;
      color: #6b798e;
    }
    .right {
      margin-left: 18px;
    }
    .tooltip-p {
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
  &-table {
    width: 100%;
    height: 272px;
  }
}
</style>

<style lang="scss" scoped>
.commonTable {
  position: relative;
  .pagination {
    position: absolute;
    right: 0;
    bottom: 0;
    height: 24px;
    padding: 0;
  }
  :deep(.el-pagination__total) {
    display: none;
  }
  :deep(.el-pagination__jump) {
    display: none;
  }
  :deep(.el-pager li.is-active) {
    font-weight: 900;
  }
}
</style>